package com.dycong.common.network.HttpInterceptor;

import org.apache.http.*;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author dycong
 * @date 2018/3/20 9:32
 */
public class TestInterceptor {
    /**
     *  todo http拦截器 协议拦截器也可以通过共享信息来共同合作-比如处理状态-通过HTTP执行上下文。协议拦截器可以使用HTTP内容来为一个或多个连续的请求存储一个处理状态。
     *  todo 通常拦截器执行的顺序不应该和它们基于的特定执行上下文状态有关。如果协议拦截器有相互依存关系，那么它们必须按特定顺序来执行，正如它们希望执行的顺序一样，它们应该在相同
     *  todo 的序列中被加到协议处理器。
     *  todo 协议拦截器必须实现为线程安全的。和Servlet相似，协议拦截器不应该使用实例变量，除非访问的那些变量是同步的。
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        CloseableHttpClient httpclient = HttpClients.custom().addInterceptorFirst(new HttpRequestInterceptor() {
            @Override
            public void process(final HttpRequest request,
                                final HttpContext context) throws HttpException, IOException {
                AtomicInteger count = (AtomicInteger) context.getAttribute("count");
                if (count == null) {
                    count = new AtomicInteger(1);
                    context.setAttribute("count", count);
                } else {
                    request.addHeader("Count", Integer.toString(count.getAndIncrement()));
                }
            }
        }).build();


        HttpGet httpget = new HttpGet("http://localhost/");
        for (int i = 0; i < 10; i++) {
            HttpResponse response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                entity.consumeContent();
            }
        }

    }
}
